/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jsysacc.asistencia.view.gui.maestros;

import com.cerd.util.BaseSP01.JUtilBaseSP01;
import com.jsysacc.asistencia.model.beans.maestros.Via;
import com.jsysacc.asistencia.model.logic.maestros.ViaLogic;
import com.jsysacc.asistencia.view.resources.commons.JLogicInterfaz;
import com.jsysacc.asistencia.view.resources.commons.JTextFieldToUpperCase;
import java.awt.Color;
import java.awt.SystemColor;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

/**
 *
 * @author Carlos
 */
public class FormDialogListVia extends javax.swing.JDialog implements JLogicInterfaz {

    //Creacion de los atributos
    private ArrayList<Via> lista = null;
    ViaLogic logic = new ViaLogic();
    DefaultTableModel modelo = null;
    JUtilBaseSP01 JUB = new JUtilBaseSP01();

    private final ResourceBundle rbMensajes = ResourceBundle.getBundle("com.jsysacc.asistencia.view.resources.commons.Mensajes");
    private final ResourceBundle rbMainMenu = ResourceBundle.getBundle("com.jsysacc.asistencia.view.resources.commons.MainMenu");

    //Variables locales
    private String criterio;
    private String valor;

    public FormDialogListVia(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initMaster();
    }

    //Metodos
    private void refreshData() {
        getEntity();
        try {
            lista = logic.getByCriterio(criterio, valor);
            llenarData(lista);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), rbMensajes.getString("MSG_MEN_PRI"), 0);
        }

    }

    private void formateoGrilla() {
        try {
            modelo = new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int rowIndex, int vColIndex) {
                    return false;
                }
            };

            modelo.setColumnCount(0);
            modelo.addColumn("<html><b>CODIGO</b></html>");
            modelo.addColumn("<html><b>DESCRIPCION</b></html>");
            modelo.addColumn("<html><b>ESTADO</b></html>");

            jtbDatos.setModel(modelo);
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
            DefaultTableCellRenderer tcr1 = (DefaultTableCellRenderer) jtbDatos.getTableHeader().getDefaultRenderer();
            tcr1.setHorizontalAlignment(JLabel.CENTER);
            tcr.setHorizontalAlignment(SwingConstants.CENTER);
            JTableHeader header = jtbDatos.getTableHeader();

            header.setDefaultRenderer(tcr1);

            TableColumn columna = null;
            columna = jtbDatos.getColumn("<html><b>CODIGO</b></html>");
            columna.setCellRenderer(tcr);
            columna.setPreferredWidth(50);
            columna = jtbDatos.getColumn("<html><b>DESCRIPCION</b></html>");
            columna.setPreferredWidth(200);
            columna = jtbDatos.getColumn("<html><b>ESTADO</b></html>");
            columna.setCellRenderer(tcr);
            columna.setPreferredWidth(50);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), rbMensajes.getString("MSG_MEN_PRI"), 0);
        }
    }

    private void llenarData(ArrayList<Via> lista) {
        try {
            //LIMPIO
            for (int i = 0; i < modelo.getRowCount(); i++) {
                modelo.removeRow(i);
            }
            modelo.setNumRows(lista.size());
            //LLENO
            for (int i = 0; i < lista.size(); i++) {
                modelo.setValueAt(lista.get(i).getCod_via(), i, 0);
                modelo.setValueAt(lista.get(i).getDescrip(), i, 1);
                modelo.setValueAt(lista.get(i).getEstado(), i, 2);
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), rbMensajes.getString("MSG_MEN_PRI"), 0);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbDatos = new javax.swing.JTable();
        jbtnAgregar = new javax.swing.JButton();
        jbtnModificar = new javax.swing.JButton();
        jbtnEliminar = new javax.swing.JButton();
        jbtnCerrar = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtxtValorBuscado = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jcbCriterio = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTabbedPane2.setFocusable(false);

        jtbDatos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtbDatos.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jtbDatos.setFocusable(false);
        jtbDatos.getTableHeader().setResizingAllowed(false);
        jtbDatos.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jtbDatos);

        jbtnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_agregar_24.png"))); // NOI18N
        jbtnAgregar.setText("Agregar");
        jbtnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAgregarActionPerformed(evt);
            }
        });

        jbtnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_modificar_24.png"))); // NOI18N
        jbtnModificar.setText("Modificar");
        jbtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnModificarActionPerformed(evt);
            }
        });

        jbtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_eliminar_24.png"))); // NOI18N
        jbtnEliminar.setText("Eliminar");
        jbtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminarActionPerformed(evt);
            }
        });

        jbtnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_cerrar_24.png"))); // NOI18N
        jbtnCerrar.setText("Cerrar");
        jbtnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jbtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jbtnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane2.addTab("Lista", new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_16_16/data.png")), jPanel2); // NOI18N

        jTabbedPane1.setFocusable(false);

        jLabel1.setText("Valor");

        jtxtValorBuscado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtxtValorBuscadoKeyReleased(evt);
            }
        });

        jLabel2.setText("Criterio ");

        jcbCriterio.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TODOS", "CODIGO", "DESCRIPCION" }));
        jcbCriterio.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbCriterioItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jcbCriterio, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtxtValorBuscado, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(47, 47, 47))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(jcbCriterio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jtxtValorBuscado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Panel de Busqueda", new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_16_16/btn_panel_busqueda_16.png")), jPanel1); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 595, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 595, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTabbedPane2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCerrarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jbtnCerrarActionPerformed

    private void jbtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminarActionPerformed
        // TODO add your handling code here:
        int rpta;
        String codigo = "";
        String mensaje = "";
        int c = 0;

        if (jtbDatos.getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_NO_SEL_DEL"), rbMensajes.getString("MSG_MEN_PRI"), 1);
        } else {
            rpta = JOptionPane.showConfirmDialog(this, rbMensajes.getString("MSG_DEL_QST"), rbMensajes.getString("MSG_MEN_PRI"), 0, 3);
            if (rpta == 0) {
                for (Integer i : jtbDatos.getSelectedRows()) {
                    codigo = jtbDatos.getValueAt(i, 0).toString();
                    try {
                        if (!logic.delete(codigo)) {
                            mensaje += (c + 1) + ".- " + rbMensajes.getString("MSG_DEL_ERROR") + " " + codigo + " \n";
                        } else {
                            mensaje += (c + 1) + ".- " + rbMensajes.getString("MSG_DEL_OK") + " " + codigo + " \n";
                        }
                    } catch (Exception ex) {
                        mensaje += (c + 1) + ".- " + rbMensajes.getString("MSG_DEL_ERROR") + " " + codigo + " \n";
                    } finally {
                        c++;
                    }
                }
                JOptionPane.showMessageDialog(this, mensaje, rbMensajes.getString("MSG_MEN_PRI"), 1);
                refreshData();
            }
        }

    }//GEN-LAST:event_jbtnEliminarActionPerformed

    private void jcbCriterioItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbCriterioItemStateChanged
        // TODO add your handling code here:

        if (this.jcbCriterio.getSelectedIndex() == 0) {
            this.jtxtValorBuscado.setText("");
            this.jtxtValorBuscado.setEditable(false);
            this.jtxtValorBuscado.setBackground(SystemColor.inactiveCaption);
        } else {
            this.jtxtValorBuscado.setEditable(true);
            this.jtxtValorBuscado.setBackground(Color.WHITE);
        }
        refreshData();

    }//GEN-LAST:event_jcbCriterioItemStateChanged

    private void jbtnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAgregarActionPerformed
        // TODO add your handling code here:

        FormDialogMantVia oFormDialogMantVia = new FormDialogMantVia(null, true);
        oFormDialogMantVia.setLocationRelativeTo(null);
        oFormDialogMantVia.setEsNuevo(true);
        oFormDialogMantVia.setTitle(rbMainMenu.getString("SUB_MEN_LIS_VIA") + " > AGREGAR");
        oFormDialogMantVia.setVisible(true);
        refreshData();

    }//GEN-LAST:event_jbtnAgregarActionPerformed

    private void jbtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnModificarActionPerformed
        // TODO add your handling code here:
        String codigo = "";
        int idx_sel = 0;

        if (jtbDatos.getSelectedRowCount() == 0 || jtbDatos.getSelectedRowCount() > 1) {
            JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_NO_SEL_UPD"), rbMensajes.getString("MSG_MEN_PRI"), 1);
        } else {
            idx_sel = jtbDatos.getSelectedRow();
            codigo = jtbDatos.getValueAt(idx_sel, 0).toString();
            FormDialogMantVia oFormDialogMantVia = new FormDialogMantVia(null, true);
            oFormDialogMantVia.setLocationRelativeTo(null);
            oFormDialogMantVia.setEsNuevo(false);
            oFormDialogMantVia.setCodVia(codigo);
            oFormDialogMantVia.setTitle(rbMainMenu.getString("SUB_MEN_LIS_VIA") + " > MODIFICAR");
            oFormDialogMantVia.setVisible(true);
            refreshData();
            jtbDatos.setRowSelectionInterval(idx_sel, idx_sel);
        }

    }//GEN-LAST:event_jbtnModificarActionPerformed

    private void jtxtValorBuscadoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtxtValorBuscadoKeyReleased
        // TODO add your handling code here:
        refreshData();
    }//GEN-LAST:event_jtxtValorBuscadoKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormDialogListVia.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormDialogListVia.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormDialogListVia.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormDialogListVia.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FormDialogListVia dialog = new FormDialogListVia(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JButton jbtnAgregar;
    private javax.swing.JButton jbtnCerrar;
    private javax.swing.JButton jbtnEliminar;
    private javax.swing.JButton jbtnModificar;
    private javax.swing.JComboBox jcbCriterio;
    private javax.swing.JTable jtbDatos;
    private javax.swing.JTextField jtxtValorBuscado;
    // End of variables declaration//GEN-END:variables

    @Override
    public boolean hayErroresInput() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void getEntity() {
        criterio = JUB.toUpperBlank(this.jcbCriterio.getSelectedItem().toString());
        valor = JUB.toUpperBlank(this.jtxtValorBuscado.getText());
    }

    @Override
    public void initMaster() {
        formateoGrilla();
        refreshData();
        this.jtxtValorBuscado.setDocument(new JTextFieldToUpperCase());
        this.jtxtValorBuscado.setText("");
        this.jtxtValorBuscado.setEditable(false);
        this.jtxtValorBuscado.setBackground(SystemColor.inactiveCaption);
        this.jcbCriterio.setSelectedIndex(0);

    }

    @Override
    public void setEntity(Object entity) {

    }

}
